﻿
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;
using System.Windows.Threading;
using Jade.Tools.SL.Windows.Extensions;
using JulMar.Silverlight.Interfaces;
using JulMar.Silverlight.Mvvm;
using MediaBrowserSL.RIA.MediaBrowserServiceReference;
using MediaBrowserSL.RIA.MvvmUtils;
using MediaBrowserSL.RIA.MvvmUtils.UI;
using MediaBrowserSL.RIA.Services;
using System.ServiceModel;

namespace MediaBrowserSL.RIA.ViewModels
{
    /// <summary>
    ///  Movies View Model
    /// </summary>
    public class PageMoviesViewModel : PageViewModelBase
    {
        #region Private Member

        private IErrorVisualizer errorVisualizer;
        private ICustomMessageBoxVisualizer customMessageBoxVisualizer;
        private IManageMoviesVisualizer manageMoviesVisualizer;
        private IPlayerMoviesVisualizer playerMoviesVisualizer;
        private bool isDeleting;
        private DispatcherTimer testSelectedItemTimer;

        #endregion

        #region Public Properties

        public override string Name
        {
            get { return "Page Movies"; }
        }

        public bool IsDeleting
        {
            get
            {
                return isDeleting;
            }
            set
            {

                isDeleting = value;
                OnPropertyChanged("IsDeleting");
            }
        }

        #endregion

        #region Command

        public DelegatingCommand PrepareAddMovieCommand
        {
            get;
            private set;
        }

        public DelegatingCommand PrepareUpdateMovieCommand
        {
            get;
            private set;
        }

        public DelegatingCommand DeleteMovieCommand
        {
            get;
            private set;
        }

        public DelegatingCommand PlayVideoCmmand
        {
            get;
            private set;
        }

        #endregion

        public PageMoviesViewModel(IMediaRiaServices service)
            : base(service)
        {
            errorVisualizer = Resolve<IErrorVisualizer>();
            manageMoviesVisualizer = Resolve<IManageMoviesVisualizer>();
            customMessageBoxVisualizer = Resolve<ICustomMessageBoxVisualizer>();
            playerMoviesVisualizer = Resolve<IPlayerMoviesVisualizer>();
            PrepareAddMovieCommand = new DelegatingCommand(PrepareAddMovie);
            PrepareUpdateMovieCommand = new DelegatingCommand(PrepareUpdateMovie);
            DeleteMovieCommand = new DelegatingCommand(DeleteMovie);
            PlayVideoCmmand = new DelegatingCommand(PlayVideo);

            testSelectedItemTimer = new DispatcherTimer();
            testSelectedItemTimer.Interval = new TimeSpan(0, 0, 0, 0, 100);
            testSelectedItemTimer.Tick += testSelectedItemTimer_Tick;
        }

        #region private Methods

        #region GetListMediasByCategory

        /// <summary>
        /// Return Medias
        /// </summary>
        /// <param name="movies"></param>
        private void GetListMediasByCategory(IEnumerable<Media> movies, Exception ex)
        {
            if (ex == null)
            {
                if (movies != null)
                {
                    if (medias != null) { medias.Clear(); } else { medias = new ObservableCollection<Media>(); }
                    foreach (var m in movies)
                    {
                        medias.Add(m);
                    }
                    sourceMediasView.Source = medias;
                    MediasView.MoveCurrentToFirst();
                    SelectedItem = CurrentMedia;
                    sourceMediasView.View.CurrentChanged += View_CurrentChanged;
                    OnPropertyChanged("MediasView");
                    View_CurrentChanged(null, null);
                }
            }
            else
            {
                if (customMessageBoxVisualizer != null)
                {
                    customMessageBoxVisualizer.Show(null, ((FaultException<ErrorDataContract>)ex).Detail.Detail, ex.Message, MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }

        void View_CurrentChanged(object sender, EventArgs e)
        {
            if (CurrentMedia != null)
            {
                lastMediaSelected = CurrentMedia;
                testSelectedItemTimer.Stop();
                testSelectedItemTimer.Start();
                OnPropertyChanged("CurrentMedia");
            }
        }

        void testSelectedItemTimer_Tick(object sender, EventArgs e)
        {
            testSelectedItemTimer.Stop();
            if (CurrentMedia == null)
            {
                sourceMediasView.View.CurrentChanged -= View_CurrentChanged;
                MediasView.MoveCurrentTo(lastMediaSelected);
                sourceMediasView.View.CurrentChanged += View_CurrentChanged;
            }
        }

        #endregion

        #region Add/Update Movie

        /// <summary>
        /// Prepare Add Movie
        /// </summary>
        private void PrepareAddMovie()
        {
            if (manageMoviesVisualizer != null) manageMoviesVisualizer.Show();
            SendMessage(MediatorMessages.EditMovie, new Media());
        }

        /// <summary>
        /// Prepare Update Movie
        /// </summary>
        private void PrepareUpdateMovie()
        {
            if (CurrentMedia != null)
            {
                if (manageMoviesVisualizer != null) manageMoviesVisualizer.Show();
                SendMessage(MediatorMessages.EditMovie, CurrentMedia);
            }
        }

        #endregion

        #region Delete Movie

        /// <summary>
        /// Delete Movie
        /// </summary>
        private void DeleteMovie()
        {
            if ((CurrentMedia != null && !IsDeleting))
            {
                if (customMessageBoxVisualizer != null)
                {
                    customMessageBoxVisualizer.Show(ConfirmDeleteMovie, "Etes-vous sur de vouloir supprimer ce film ?", "Supprimer", MessageBoxButton.OKCancel, MessageBoxImage.Question);
                }
                else
                {
                    IsDeleting = true;
                    service.DeleteMedia(MediaDeleted, CurrentMedia, SessionMb.CurrentUser);
                }
            }
        }

        /// <summary>
        /// Confirm Delete Movie
        /// </summary>
        /// <param name="r"></param>
        private void ConfirmDeleteMovie(MessageBoxResult r)
        {
            if (r == MessageBoxResult.OK)
            {
                IsDeleting = true;
                service.DeleteMedia(MediaDeleted, CurrentMedia, SessionMb.CurrentUser);
            }
        }

        /// <summary>
        /// Media Deleted
        /// </summary>
        /// <param name="e"></param>
        private void MediaDeleted(Exception ex)
        {
            IsDeleting = false;
            if (ex == null)
            {
                CurrentMedia.UrlImage = null;
                if (medias != null) { medias.Remove(CurrentMedia); }
                OnPropertyChanged("CurrentMedia");
            }
            else
            {
                if (customMessageBoxVisualizer != null)
                {
                    customMessageBoxVisualizer.Show(null, ((FaultException<ErrorDataContract>)ex).Detail.Detail, ex.Message, MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }

        #endregion

        /// <summary>
        /// Play Video Movie
        /// </summary>
        private void PlayVideo()
        {
            if (CurrentMedia != null)
            {
                if (playerMoviesVisualizer != null)
                {
                    playerMoviesVisualizer.Show();
                    SendMessage(MediatorMessages.PlayeMovie, CurrentMedia);
                }
            }
        }

        #endregion

        #region Public Methods

        /// <summary>
        /// Update Current User
        /// </summary>
        /// <param name="page"></param>
        [MessageMediatorTarget(MediatorMessages.UpdateCurrentUser)]
        public void UpdateCurrentUser(User user)
        {
            service.GetListMediasByCategory(GetListMediasByCategory, SessionMb.CurrentUser.Id, 1);
        }

        /// <summary>
        /// LogOut
        /// </summary>
        [MessageMediatorTarget(MediatorMessages.LogOut)]
        public void LogOut(User user)
        {
            if (medias != null)
            {
                MediasView.MoveCurrentToFirst();
                if (CurrentMedia != null)
                {
                    CurrentMedia.UrlImage = null;
                }
                medias.Clear();
                MediaLookFor = String.Empty;
                OnPropertyChanged("CurrentMedia");
            }
            else
            {
                medias = new ObservableCollection<Media>();
            }
        }

        /// <summary>
        /// Add Movie to List
        /// </summary>
        /// <param name="page"></param>
        [MessageMediatorTarget(MediatorMessages.AddMovieToList)]
        public void AddMovieToList(Media m)
        {
            if (medias != null) { medias.Add(m); }
            MediasView.MoveCurrentToLast();
        }

        /// <summary>
        /// Update Movie to List
        /// </summary>
        /// <param name="page"></param>
        [MessageMediatorTarget(MediatorMessages.UpdateMovieToList)]
        public void UpdateMovieToList(Media m)
        {
            var movie = (from mo in Medias where m.Id == mo.Id select mo).SingleOrDefault();
            movie.Name = m.Name;
            movie.Description = m.Description;
        }

        #endregion
    }
}
